import {
    cumulativeHotOfScore,
    obtainScoreDetails,
    appendScoreToCollect,
    removeScoreToCollect
} from '../../../config/api'
import * as actionTypes from './actionTypes';
import { downLoadFileFromOSS } from '../../../config/utils';
import axios from 'axios';
import JsZip from 'jszip';
import { saveAs } from 'file-saver';

const getScoreParticulars = (data) => ({
	type: actionTypes.Get_Score_Particulars,
	data
});
const appendScoreCollect = () => ({
    type: actionTypes.Add_Score_Collect
})
const removeScoreCollect = () => ({
	type: actionTypes.Sub_Score_Collect
})

// 累加 曲谱浏览量
export const accumulateHotOfScore = ( score_id ) => {
    return async (dispatch) => {
        const resultInfo =  await cumulativeHotOfScore( score_id )
        if (resultInfo.status === 200) {}
    };
}; 
// 获取 曲谱详情 数据
export const acquireScoreParticularsData = ( score_id, open_id, union_id ) => {
	return async (dispatch) => {
		const resultInfo = await obtainScoreDetails( score_id, open_id, union_id )
		if (resultInfo.status === 200) {
			dispatch(getScoreParticulars(resultInfo.data));
		}
	}
};
// 收藏 图谱到曲谱库
export const enshrineScoreToLibrary = ( score_id, open_id, union_id ) => {
    return async (dispatch) => {
        const resultInfo = await appendScoreToCollect( score_id, open_id, union_id )
		console.log(resultInfo, '...resultInfo')
		// if (resultInfo.status === 200) {
			dispatch(appendScoreCollect());
		// }
    }
};
// 移除 图谱于曲谱库
export const removalScoreFromLibrary = ( score_id, open_id, union_id ) => {
    return async (dispatch) => {
        const resultInfo = await removeScoreToCollect( score_id, open_id, union_id )
		console.log(resultInfo, '...resultInfo')
		// if (resultInfo.status === 200) {
			dispatch(removeScoreCollect());
		// }
    }
};

// 获取曲谱图片数据
const acquireScoreImageData = (url) => {
    return new Promise((resolve, reject) => {
        axios({
            method:'get',
            url,
            responseType: 'arraybuffer'
        }).then(data => {
            resolve(data.data)
        }).catch(error => {
            reject(error.toString())
        })
    })
}


// 下载 曲谱于曲谱库
export const downloadScoreFromLibrary = ( imgList, name ) => {
    return async (dispatch) => {
        const zip = new JsZip();

        // zip.file("Hello.txt", "Hello World\n");
        // zip.generateAsync({type:"blob"}).then(function(content) {
        //     // see FileSaver.js
        //     saveAs(content, "example.zip");
        //     // console.log(content, "example.zip")
        // });

        // imgList.map(async (item, index) => {
        for (let i = 0; i < imgList.length; i++) {
            // window.open(await downLoadFileFromOSS(imgList[i]), '_blank');

            // var iframe = document.createElement("iframe")
            // iframe.style.display = "none";
            // iframe.src = await downLoadFileFromOSS(imgList[i]);
            // document.body.appendChild(iframe);

            const urlOSS = await downLoadFileFromOSS(imgList[i], 'songlibs');
            if (urlOSS) {
            //     // 创建隐藏的可下载链接
            //     let eleLink = document.createElement('a');
            //     eleLink.id='downLoad'+i;
            //     eleLink.download = urlOSS;
            //     eleLink.style.display = 'none';
            //     // 字符内容转变成blob地址
            //     eleLink.href = urlOSS;
            //     // 触发点击
            //     document.body.appendChild(eleLink);
            //     eleLink.click();
            //     console.log(eleLink)
            //     // 然后移除
            //     document.body.removeChild(eleLink);

                const resultInfo = await acquireScoreImageData(urlOSS)
                console.log(resultInfo, '....resultInfo', i)
                // 逐个添加文件
                zip.file(name+'_'+(i+1)+'.jpg', resultInfo, { binary: true })
                if (i === imgList.length-1) {
                    zip.generateAsync({type:"blob"}).then(function(content) {
                        // see FileSaver.js
                        saveAs(content, name+".zip");
                        // console.log(content, "example.zip")
                    });
                }
            }
        }
        // })
        




        // const urlOSS = await downLoadFileFromOSS(url);
        // if (urlOSS) {
        //     // console.log(urlOSS, '...urlOSS')
        //     // axios.get(urlOSS).then((res) => {
        //     //     // console.log(res, '...res')
        //     //     let content = 'http://mobuz-live.oss-cn-hangzhou.aliyuncs.com/songlibs/xL9RSbVlpp.jpg';
        //     //     let blob = new Blob([content]);
        //     //     let link = document.createElement('a');
        //     //     // link.download = "file.jpg";
        //     //     link.href =  URL.createObjectURL(blob);
        //     //     link.click();
        //     // }).catch(() => {
                
        //     // })
        //     // window.open(urlOSS, '_blank')

        //     // let canvas = document.createElement('canvas');
        //     // let img = document.createElement('img');
        //     // img.onload = function(e) {
        //     //     canvas.width = img.width;
        //     //     canvas.height = img.height;
        //     //     let context = canvas.getContext('2d');
        //     //     context.drawImage(img, 0, 0, img.width, img.height);
        //     //     window.navigator.msSaveBlob(canvas.msToBlob(), 'image.jpg');
        //     //     console.log(canvas.width)
        //     // }
        //     // img.src = urlOSS;

        //     // var iframe = document.createElement("iframe")
        //     // iframe.style.display = "none";
        //     // iframe.src = urlOSS;
        //     // document.body.appendChild(iframe);

        //     // 创建隐藏的可下载链接
        //     var eleLink = document.createElement('a');
        //     eleLink.download = urlOSS;
        //     eleLink.style.display = 'none';
        //     // // 字符内容转变成blob地址
        //     eleLink.href = urlOSS;
        //     // // 触发点击
        //     document.body.appendChild(eleLink);
        //     eleLink.click();
        //     // // 然后移除
        //     document.body.removeChild(eleLink);

        //     // var a = document.createElement('a');
        //     // a.href = urlOSS;
        //     // a.download = "proposed_file_name";
        //     // a.click();

        //     // let content = 'http://mobuz-live.oss-cn-hangzhou.aliyuncs.com/songlibs/xL9RSbVlpp.jpg?OSSAccessKeyId=LTAIzsvPrCVvXfRA&Expires=1550222686&Signature=iemcwXuWGBNgmQkZ72dNftX4twU%3D';
        //     // let blob = new Blob([content]);
        //     // let link = document.createElement('a');
        //     // link.download = "file.jpg";
        //     // link.href = URL.createObjectURL(blob);
        //     // link.click();

            

        // }
    }
}
